package com.dragon.gencode.util;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @ClassName BeanUtils
 * @Description TODO
 * @Author dragon
 * @Date 2020-06-17 17:48
 * @Version 1.0
 **/
public class BeanUtils {

    public static ObjectMapper mapper = new ObjectMapper();
    static{
        // map 字段 多了 报错 处理
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static <T> List<T> toBeanList(List<Map<String, Object>> maps, Class<T> tClass) {
        ArrayList<T> list = new ArrayList<>();
        if (maps != null && maps.size() > 0) {
            maps.forEach(map -> list.add(toBean(map, tClass)));
        }
        return list;
    }

    public static <T> List<T> toBeanList(List<Map<String, Object>> maps, Class<T> tClass, Function<String, String> key2key,Function<Object, Object> value2value) {
        ArrayList<T> list = new ArrayList<>();
        if (maps != null && maps.size() > 0) {
            maps.forEach(map -> list.add(toBean(map, tClass, key2key,value2value)));
        }
        return list;
    }

    public static <T> T toBean(Map<String, Object> map, Class<T> tClass) {
        return toBean(map, tClass, null, null);
    }

    /**
     * @param map
     * @param tClass
     * @param key2key map中key不符合要求，需要转换可以 如key=USER_NAME 转换为 userName :: eg:k -> com.dragon.gencode.common.utils.StringUtils.toCamelCase(k)
     * @param <T>
     * @return
     */
    public static <T> T toBean(Map<String, Object> map, Class<T> tClass, Function<String, String> key2key,Function<Object, Object> value2value) {
        Map<String, Object> temp = new HashMap<>();
        if (key2key != null || value2value != null) {
            Map<String, Object> m = new HashMap<>();
            map.forEach((k, v) -> {
                String k2k = (key2key != null)?key2key.apply(k):k;
                Object v2v = (value2value != null)?value2value.apply(v):v;
                m.put(k2k, v2v);
            });
            temp.putAll(m);
        }else {
            temp.putAll(map);
        }

        try {
            return mapper.convertValue(temp, tClass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
